package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.AbnormalBike;
import com.tbit.uqbike.client.pojo.Machine;
import com.tbit.uqbike.client.service.AbnormalBikeService;
import com.tbit.uqbike.client.service.MachineService;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常车辆
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Controller
@RequestMapping("/abnormalBike")
public class AbnormalBikeController {
    @Autowired
    private AbnormalBikeService abnormalBikeService;
    @Autowired
    private MachineService machineService;


    /**
     * 添加
     *
     * @param token        令牌
     * @param type         类型
     * @param abnormalBike 不正常自行车
     * @param session      会话
     * @param response     响应
     * @ignoreParams request
     */
    @RequestMapping("/add")
    public void add(String token, String type, AbnormalBike abnormalBike, HttpSession session,
                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            /* 校验 */
            Assert.hasLength(abnormalBike.getMachineNO(), "-30001", "编号不能为空");
            Assert.notNull(type, "-80001", "异常信息不能为空");

            String[] strings = type.split(",");

            /**判断编号是否存在*/
            Machine machine = machineService.getByMachineNO(abnormalBike.getMachineNO());
            if (machine == null) {
                throw new BaseException("-30005", "设备不存在");
            }

            abnormalBike.setMachineId(machine.getMachineId());
            for (int i = 0; i < strings.length; i++) {
                abnormalBike.setAbnormalType(Integer.valueOf(strings[i]));
                abnormalBikeService.insert(abnormalBike);
            }


            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

}